document.addEventListener('DOMContentLoaded', function() {
    const BASE_URL = window.BASE_URL || '/AVR';
    const userId = userId2; // 固定用户ID
    const myServicesContainer = document.getElementById('my-services-container');
    const noServicesMessage = document.getElementById('no-services-message');
    const editServiceModal = document.getElementById('edit-service-modal');
    const closeEditModal = document.getElementById('close-edit-modal');
    const cancelEditBtn = document.getElementById('cancel-edit');
    const editServiceForm = document.getElementById('edit-service-form');

    // 音频播放器实例
    let audioPlayer = null;

    // 关闭编辑模态框
    if (closeEditModal) {
        closeEditModal.addEventListener('click', () => {
            editServiceModal.style.display = 'none';
        });
    }

    if (cancelEditBtn) {
        cancelEditBtn.addEventListener('click', () => {
            editServiceModal.style.display = 'none';
        });
    }

    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === editServiceModal) {
            editServiceModal.style.display = 'none';
        }
    });

    // 获取当前用户的陪玩服务
    async function fetchMyServices() {
        try {
            // 使用现有的筛选接口，添加 userId 参数
            const response = await fetch(`${BASE_URL}/accompanys/search?userId=${userId}`);

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP ${response.status}: ${errorText}`);
            }

            const result = await response.json();

            // 检查返回的数据结构
            console.log('My services response:', result);

            if (result.code === 20021) { // selectByConditions_OK
                return result.data;
            } else {
                throw new Error(result.msg || '获取数据失败');
            }
        } catch (error) {
            console.error('请求失败:', error);
            showErrorToast(`数据加载失败: ${error.message}`);
            return [];
        }
    }

    // 渲染我的陪玩服务
    function renderMyServices(services) {
        myServicesContainer.innerHTML = '';

        if (services.length === 0) {
            noServicesMessage.style.display = 'block';
            return;
        }

        noServicesMessage.style.display = 'none';

        services.forEach(service => {
            // 处理图片URL
            const images = typeof service.imageUrls === 'string'
                ? service.imageUrls.split(',')
                : service.imageUrls || [];

            const firstImage = images[0] || 'https://via.placeholder.com/300x200?text=No+Image';

            const card = document.createElement('div');
            card.className = 'my-service-card';
            card.innerHTML = `
                <div class="my-card-image">
                    <img src="${firstImage}" alt="${service.gameType}陪玩">
                    <div class="my-card-badge">${service.serviceType}</div>
                </div>
                <div class="my-card-content">
                    <h3 class="my-card-title">${service.gameType}专业陪玩</h3>
                    <div class="my-card-meta">
                        <span class="game-type">${service.gameType}</span>
                        <span class="service-type">${service.serviceType}</span>
                    </div>
                    <div class="my-card-price">￥${service.price.toFixed(2)} <span class="price-unit">/小时</span></div>
                    <p class="my-card-description">${service.description.substring(0, 100)}${service.description.length > 100 ? '...' : ''}</p>
                    <div class="my-card-actions">
                        <a href="#" class="edit-btn" data-id="${service.id}">
                            <i class="fas fa-edit"></i> 编辑
                        </a>
                        <a href="#" class="delete-btn" data-id="${service.id}">
                            <i class="fas fa-trash"></i> 删除
                        </a>
                    </div>
                </div>
            `;
            myServicesContainer.appendChild(card);
        });

        // 添加编辑事件监听
        document.querySelectorAll('.edit-btn').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const serviceId = this.getAttribute('data-id');
                openEditModal(serviceId, services);
            });
        });

        // 添加删除事件监听
        document.querySelectorAll('.delete-btn').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const serviceId = this.getAttribute('data-id');
                deleteService(serviceId);
            });
        });
    }

    // 打开编辑模态框
    function openEditModal(serviceId, services) {
        const service = services.find(s => s.id === parseInt(serviceId));
        if (service) {
            document.getElementById('edit-id').value = service.id;
            document.getElementById('edit-game-type').value = service.gameType;
            document.getElementById('edit-service-type').value = service.serviceType;
            document.getElementById('edit-description').value = service.description;
            document.getElementById('edit-price').value = service.price;
            document.getElementById('edit-contact').value = service.contact;

            // 添加图片预览
            const imagePreview = document.getElementById('edit-image-preview');
            imagePreview.innerHTML = '';

            const images = typeof service.imageUrls === 'string'
                ? service.imageUrls.split(',')
                : service.imageUrls || [];

            images.forEach((imgUrl, index) => {
                if (imgUrl) {
                    const previewItem = document.createElement('div');
                    previewItem.className = 'image-preview-item';
                    previewItem.innerHTML = `
                        <img src="${imgUrl}" alt="预览图片">
                    `;
                    imagePreview.appendChild(previewItem);
                }
            });

            // 设置当前音频
            const currentPlayBtn = document.getElementById('current-play-btn');
            if (service.audioUrl) {
                // 设置音频URL
                currentPlayBtn.setAttribute('data-audio', service.audioUrl);

                // 更新音频信息
                const audioInfo = document.querySelector('#current-voice-player .voice-info');
                audioInfo.innerHTML = `
                    <div>当前语音介绍</div>
                    <p>点击播放按钮</p>
                `;
            } else {
                currentPlayBtn.removeAttribute('data-audio');
                const audioInfo = document.querySelector('#current-voice-player .voice-info');
                audioInfo.innerHTML = `
                    <div>无语音介绍</div>
                    <p>请上传新语音</p>
                `;
            }

            // 重置新音频预览
            document.getElementById('edit-audio-preview').innerHTML = '';
            document.getElementById('edit-audio').value = '';

            // 添加新音频上传预览
            const audioInput = document.getElementById('edit-audio');
            if (audioInput) {
                audioInput.addEventListener('change', function(e) {
                    const audioPreview = document.getElementById('edit-audio-preview');
                    audioPreview.innerHTML = '';
                    const file = e.target.files[0];

                    if (file) {
                        const previewItem = document.createElement('div');
                        previewItem.className = 'audio-preview-item';
                        previewItem.innerHTML = `
                            <i class="fas fa-volume-up"></i>
                            <div>${file.name}</div>
                            <div class="play-preview-btn" data-file="${URL.createObjectURL(file)}">
                                <i class="fas fa-play"></i> 试听
                            </div>
                        `;
                        audioPreview.appendChild(previewItem);

                        // 添加试听按钮事件
                        previewItem.querySelector('.play-preview-btn').addEventListener('click', function() {
                            const fileUrl = this.getAttribute('data-file');
                            playAudio(fileUrl);
                        });
                    }
                });
            }

            editServiceModal.style.display = 'flex';
        }
    }

    // 播放音频函数
    function playAudio(url) {
        // 停止当前播放
        if (audioPlayer) {
            audioPlayer.pause();
            audioPlayer = null;
        }

        if (!url) {
            showErrorToast('语音介绍不可用');
            return;
        }

        try {
            // 处理相对路径的音频URL
            const fullAudioUrl = url.startsWith('http') ? url : `${BASE_URL}${url.startsWith('/') ? '' : '/'}${url}`;

            audioPlayer = new Audio(fullAudioUrl);
            audioPlayer.play().catch(e => {
                console.error('播放失败:', e);
                showErrorToast('播放失败: 请检查音频地址');
            });

            // 更新播放按钮状态
            const playBtn = document.getElementById('current-play-btn');
            if (playBtn) {
                const icon = playBtn.querySelector('i');
                icon.className = 'fas fa-pause';

                audioPlayer.addEventListener('ended', () => {
                    icon.className = 'fas fa-play';
                });
            }
        } catch (e) {
            console.error('音频创建失败:', e);
            showErrorToast('音频格式不支持');
        }
    }

    // 当前音频播放按钮点击事件
    document.getElementById('current-play-btn').addEventListener('click', function() {
        const audioUrl = this.getAttribute('data-audio');
        if (audioUrl) {
            // 如果正在播放，则暂停
            if (audioPlayer && !audioPlayer.paused) {
                audioPlayer.pause();
                this.querySelector('i').className = 'fas fa-play';
            } else {
                playAudio(audioUrl);
            }
        } else {
            showErrorToast('没有可播放的音频');
        }
    });

    // 上传文件到OSS
    async function uploadFileToOss(file, policy, dir) {
        return new Promise((resolve, reject) => {
            const formData = new FormData();

            // 确保目录格式正确
            const normalizedDir = dir.endsWith('/') ? dir : dir + '/';
            const key = normalizedDir + file.name;

            formData.append('key', key);
            formData.append('policy', policy.policy);
            formData.append('OSSAccessKeyId', policy.accessid);
            formData.append('signature', policy.signature);
            formData.append('success_action_status', '200');
            formData.append('file', file);

            fetch(policy.host, {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    if (response.status === 200) {
                        const fileUrl = `${policy.host}/${key}`;
                        resolve(fileUrl);
                    } else {
                        response.text().then(text => {
                            reject(`上传失败: ${response.status} - ${text}`);
                        });
                    }
                })
                .catch(error => {
                    reject(`上传错误: ${error.message}`);
                });
        });
    }

    // 删除服务
    async function deleteService(serviceId) {
        if (!confirm('确定要删除这个陪玩服务吗？此操作不可撤销。')) {
            return;
        }

        try {
            const response = await fetch(`${BASE_URL}/accompanys/${serviceId}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP ${response.status}: ${errorText}`);
            }

            const result = await response.json();

            if (result.code === 20051) { // 删除成功
                showSuccessToast('服务删除成功');
                // 刷新列表
                const services = await fetchMyServices();
                renderMyServices(services);
            } else {
                throw new Error(result.msg || '删除失败');
            }
        } catch (error) {
            console.error('删除失败:', error);
            showErrorToast(`删除失败: ${error.message}`);
        }
    }

    // 编辑表单提交
    if (editServiceForm) {
        editServiceForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            const serviceId = document.getElementById('edit-id').value;
            const gameType = document.getElementById('edit-game-type').value;
            const serviceType = document.getElementById('edit-service-type').value;
            const description = document.getElementById('edit-description').value;
            const price = parseFloat(document.getElementById('edit-price').value);
            const contact = document.getElementById('edit-contact').value;
            const newAudioFile = document.getElementById('edit-audio').files[0];

            // 验证数据
            if (!gameType || !serviceType || !description || isNaN(price) || !contact) {
                showErrorToast('请填写所有必填字段');
                return;
            }

            try {
                let newAudioUrl = null;

                // 如果有新音频文件，上传到OSS
                if (newAudioFile) {
                    // 1. 获取OSS上传策略
                    const policyResponse = await fetch(`${BASE_URL}/oss/policy`);
                    if (!policyResponse.ok) {
                        throw new Error('获取上传凭证失败: ' + await policyResponse.text());
                    }
                    const policy = await policyResponse.json();
                    const dir = policy.dir || 'accompany/' + Date.now() + '/';

                    // 2. 上传音频
                    newAudioUrl = await uploadFileToOss(newAudioFile, policy, dir);
                }

                // 创建服务数据
                const serviceData = {
                    id: serviceId,
                    gameType: gameType,
                    serviceType: serviceType,
                    description: description,
                    price: price,
                    contact: contact,
                    userId: userId
                };

                // 如果有新音频URL，添加到数据
                if (newAudioUrl) {
                    serviceData.audioUrl = newAudioUrl;
                }

                // 提交服务数据
                const response = await fetch(`${BASE_URL}/accompanys`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(serviceData)
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`服务提交失败: ${response.status} - ${errorText}`);
                }

                const result = await response.json();

                if (result.code === 20041) { // 更新成功
                    showSuccessToast('服务更新成功');
                    editServiceModal.style.display = 'none';

                    // 刷新列表
                    const services = await fetchMyServices();
                    renderMyServices(services);
                } else {
                    throw new Error(result.msg || '更新失败');
                }
            } catch (error) {
                console.error('更新失败:', error);
                showErrorToast(`更新失败: ${error.message}`);
            }
        });
    }

    // 显示成功提示
    function showSuccessToast(message) {
        const toast = document.createElement('div');
        toast.className = 'success-toast';
        toast.innerHTML = `
            <i class="fas fa-check-circle"></i>
            <span>${message}</span>
        `;

        document.body.appendChild(toast);

        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // 显示错误提示
    function showErrorToast(message) {
        const toast = document.createElement('div');
        toast.className = 'error-toast';
        toast.innerHTML = `
            <i class="fas fa-exclamation-circle"></i>
            <span>${message}</span>
        `;

        document.body.appendChild(toast);

        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // 初始化加载数据
    async function init() {
        try {
            const services = await fetchMyServices();
            renderMyServices(services);
        } catch (error) {
            console.error('初始化失败:', error);
        }
    }

    init();

    // 设置全局BASE_URL
    window.BASE_URL = BASE_URL;
});